/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ucjava.chat.commserve.rmi.guiclient;

import com.ucjava.chat.commserve.rmi.common.Message;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.DefaultListModel;
import javax.swing.JList;


/**
 * Uses a JList for its display surface.
 *
 * @author tony
 */
public class JListClientDisplay extends JList
        implements IClientDisplay
{
    private DefaultListModel messageDisplayModel;
    private String timeFormat = null;
    private String usernameFormat = null;
    
    // set display formats for timestamp:
    @Override
    public void setTimeFormat(String f)
    {
        if (f != null &&
                ! f.isEmpty())
          {
            timeFormat = f;
          }
    }
    // set display format for user name -- how many characters
    @Override
    public void setusernameFormat(String f)
    {
        if (f != null &&
                ! f.isEmpty())
          {
            usernameFormat = f;
          }
    }
    
    /**
     * Initialize the display.
     */
    @Override
    public void initMessageDisplay()
    {
        // Set this JList's message display model. Save
        // the display model in a class attribute so that
        // other methods that use it don't have to keep
        // calling getDisplayModel() -- save typing!
        messageDisplayModel = new DefaultListModel();
        this.setModel(messageDisplayModel);
    }

    /**
     * Removes messages from the display only. Does not affect any "backing
     * store" the program might have outside of this class.
     */
    @Override
    public void clearMessageDisplay()
    {
        messageDisplayModel.clear();
    }

    /**
     * Adds a single message to the message display pane. If this is the first
     * message, this method clears the "no messages yet..." message from the
     * display pane.
     *
     * 
     * @param msg
     */
    public void appendMessage(Message msg)
    {
        if (messageDisplayModel.isEmpty())
          {
            clearMessageDisplay();
          }
        // Add timestamp to beginning of output string:
        
        //SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat formatter = new SimpleDateFormat(this.timeFormat);
        Timestamp ts = new Timestamp(new Date().getTime());
        String s = formatter.format(ts) + ": "
                + String.format(this.usernameFormat, msg.getSender().getUserName()) + " "
                + msg.getContent();
        appendString(s);
    }

    /**
     * Put a string onto the display area:
     * @param str 
     */
    @Override
    public void appendString(String str)
    {
        messageDisplayModel.addElement(str);
    }
    
    
}
